package com.intelligent.system.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.system.auth.dto.ContactQueryDTO;
import com.intelligent.system.auth.entity.Contact;
import com.intelligent.system.auth.entity.Organization;
import com.intelligent.system.auth.mapper.ContactMapper;
import com.intelligent.system.auth.service.ContactService;
import com.intelligent.system.auth.service.OrganizationService;
import com.intelligent.system.auth.dto.ContactDTO;
import com.intelligent.system.auth.dto.OrganizationDTO;
import com.intelligent.system.common.exception.CustomException;
import com.intelligent.system.common.response.ResponseCode;
import com.intelligent.system.common.response.ResultDO;
import com.intelligent.system.common.utils.SnowflakeIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 联系人服务实现类
 */
@Slf4j
@Service
public class ContactServiceImpl extends ServiceImpl<ContactMapper, Contact> implements ContactService {

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private SnowflakeIdUtils idUtils;

    @Override
    public ResultDO<ContactDTO> getContactById(Long id) {
        try {
            log.info("根据ID查询联系人, id: {}", id);
            Contact contact = contactMapper.selectById(id);
            if (contact == null) {
                log.warn("联系人不存在, id: {}", id);
                throw new CustomException("联系人不存在", ResponseCode.NOT_FOUND.getCode());
            }
            ContactDTO dto = new ContactDTO();
            BeanUtils.copyProperties(contact, dto);
            return ResultDO.success(dto);
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("根据ID查询联系人异常, id: {}", id, e);
            throw new CustomException("查询联系人失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }


    @Override
    public ResultDO<List<ContactDTO>> listByOrganizationId(Long organizationId) {
        try {
            log.info("根据组织ID查询联系人列表, organizationId: {}", organizationId);
            if (organizationId == null) {
                throw new CustomException("组织机构ID不能为空", ResponseCode.BAD_REQUEST.getCode());
            }
            List<Contact> contacts = contactMapper.selectByOrganizationId(organizationId);
            List<ContactDTO> list =  contacts.stream()
                    .map(contact -> {
                        ContactDTO dto = new ContactDTO();
                        BeanUtils.copyProperties(contact, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            return ResultDO.success(list);
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("根据组织ID查询联系人列表异常, organizationId: {}", organizationId, e);
            throw new CustomException("查询联系人列表失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }



    @Override
    public ResultDO<IPage<ContactDTO>> page(ContactQueryDTO queryDTO) {
        try {
            // 构建分页对象
            Page<Contact> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

            // 构建查询条件
            LambdaQueryWrapper<Contact> wrapper = new LambdaQueryWrapper<>();

            // 添加查询条件
            wrapper.like(StringUtils.isNotBlank(queryDTO.getName()), Contact::getName, queryDTO.getName())
                    .like(StringUtils.isNotBlank(queryDTO.getPosition()), Contact::getPosition, queryDTO.getPosition())
                    .like(StringUtils.isNotBlank(queryDTO.getMobile()), Contact::getMobile, queryDTO.getMobile())
                    .like(StringUtils.isNotBlank(queryDTO.getFixedPhone()), Contact::getFixedPhone, queryDTO.getFixedPhone())
                    .eq(queryDTO.getOrganizationId() != null, Contact::getOrganizationId, queryDTO.getOrganizationId())
                    .eq(Contact::getIsDelete, 0);  // 过滤已删除记录


            // 执行分页查询
            IPage<Contact> contactPage = contactMapper.selectPage(page, wrapper);

            // 转换为DTO
            IPage<ContactDTO> dtoPage = contactPage.convert(contact -> {
                ContactDTO dto = new ContactDTO();
                BeanUtils.copyProperties(contact, dto);
                return dto;
            });

            return ResultDO.success(dtoPage);
        } catch (Exception e) {
            log.error("分页查询联系人失败", e);
            throw new CustomException("系统错误", ResponseCode.SYSTEM_ERROR.getCode());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDO<?> save(ContactDTO contactDTO) {
        try {
            log.info("新增联系人, contactDTO: {}", contactDTO);
            if (contactDTO == null) {
                throw new CustomException("联系人信息不能为空", ResponseCode.BAD_REQUEST.getCode());
            }
            // 检查手机号是否已存在
            if (contactDTO.getMobile() != null) {
                ResultDO<ContactDTO> existingContact = getByMobile(contactDTO.getMobile());
                if (existingContact.getData() != null) {
                    throw new CustomException("手机号已存在", ResponseCode.OPERATION_FAILED.getCode());
                }
            }
            Contact contact = new Contact();
            BeanUtils.copyProperties(contactDTO, contact);
            contact.setId(idUtils.nextId());

            if (this.save(contact)) {
                return ResultDO.success(null);
            }
            throw new CustomException("系统错误", ResponseCode.SYSTEM_ERROR.getCode());
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("新增联系人异常, contactDTO: {}", contactDTO, e);
            throw new CustomException("新增联系人失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDO<?> update(ContactDTO contactDTO) {
        try {
            log.info("更新联系人, contactDTO: {}", contactDTO);
            if (contactDTO == null || contactDTO.getId() == null) {
                throw new CustomException("联系人信息或ID不能为空", ResponseCode.BAD_REQUEST.getCode());
            }
            // 检查联系人是否存在
            Contact existingContact = this.getById(contactDTO.getId());
            if (existingContact == null) {
                throw new CustomException("联系人不存在", ResponseCode.NOT_FOUND.getCode());
            }
            // 检查手机号是否已被其他联系人使用
            if (contactDTO.getMobile() != null && !contactDTO.getMobile().equals(existingContact.getMobile())) {
                ResultDO<ContactDTO> contactByMobile = getByMobile(contactDTO.getMobile());
                if (contactByMobile.getData() != null && !contactByMobile.getData().getId().equals(contactDTO.getId())) {
                    throw new CustomException("手机号已被其他联系人使用", ResponseCode.OPERATION_FAILED.getCode());
                }
            }
            Contact contact = new Contact();
            BeanUtils.copyProperties(contactDTO, contact);

            if (this.updateById(contact)) {
                return ResultDO.success(null);
            }
            throw new CustomException("系统错误", ResponseCode.SYSTEM_ERROR.getCode());
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新联系人异常, contactDTO: {}", contactDTO, e);
            throw new CustomException("更新联系人失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDO<?> deleteById(Long id) {
        try {
            log.info("删除联系人, id: {}", id);
            if (id == null) {
                throw new CustomException("联系人ID不能为空", ResponseCode.BAD_REQUEST.getCode());
            }
            // 检查联系人是否存在
            Contact contact = this.getById(id);
            if (contact == null) {
                throw new CustomException("联系人不存在", ResponseCode.NOT_FOUND.getCode());
            }

            if (this.removeById(contact)) {
                return ResultDO.success(null);
            }
            throw new CustomException("系统错误", ResponseCode.SYSTEM_ERROR.getCode());
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("删除联系人异常, id: {}", id, e);
            throw new CustomException("删除联系人失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }

    @Override
    public ResultDO<ContactDTO> getByMobile(String mobile) {
        try {
            log.info("根据手机号查询联系人, mobile: {}", mobile);
            if (mobile == null || mobile.trim().isEmpty()) {
                throw new CustomException("手机号不能为空", ResponseCode.BAD_REQUEST.getCode());
            }
            Contact contact = this.getOne(new LambdaQueryWrapper<Contact>()
                    .eq(Contact::getMobile, mobile)
                    .eq(Contact::getIsDelete, 0));
            if (contact == null) {
                return ResultDO.success(null);
            }
            ContactDTO dto = new ContactDTO();
            BeanUtils.copyProperties(contact, dto);
            return ResultDO.success(dto);
        } catch (Exception e) {
            log.error("根据手机号查询联系人异常, mobile: {}", mobile, e);
            throw new CustomException("查询联系人失败", ResponseCode.SYSTEM_ERROR.getCode(), e);
        }
    }

}